﻿using GN.Pay.Utils;
using GN.Pay.Utils.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GN.Pay.TradeChannel.YJPay.Request
{
    [Serializable]
    public abstract class AServiceRequest : AService
    {

        /// <summary>
        /// Api服务名称，与服务版本一起唯一标志一个服务
        /// </summary>
        public abstract string service { get; }

        /// <summary>
        /// 	签约的商户或合作商的ID,由平台分配。定长20字符 
        /// </summary>
        public string partnerId { get; set; }


        /// <summary>
        /// 签名认证方式，可选值为MD5,SHA1和RSA，MD5为默认值
        /// </summary>
        public string signType { get; set; }

        /// <summary>
        /// 报文签名
        /// </summary>
        public string sign { get; set; }

        /// <summary>
        /// 生成签名字典
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="config"></param>
        /// <returns></returns>
        protected SignDictionary BuildSignDictionary(ITradeChannel channel, YJPayConfigure config)
        {
            this.signType = "MD5";
            var dic = this.GetSignDictionary(StringComparer.Ordinal);
            Dictionary<string, string> removeItems = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
            string key = "sign";
            string value;
            if (key != null && dic.TryGetValue(key, out value))
            {
                dic.Remove(key);
                removeItems[key] = value;
            }
            string content = dic.UrlLinkString(k =>
            {
                return k;
            }, null);
            if (string.IsNullOrWhiteSpace(content))
            {
                channel.ThrowChannelValidationException("待签名内容为null或空白字符");
            }
            this.sign = Md5Utils.Sign(string.Concat(content, config.ConfigureInfo.Key), config.Encoding);
            if (removeItems.Count > 0)
            {
                foreach (var item in removeItems)
                {
                    dic[item.Key] = item.Value;
                }
            }
            dic["sign"] = sign;
            return dic;
        }

    }
}
